//
//  ChatItemUserView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/5/2.
//

import SwiftUI
import Kingfisher

struct ChatItemUserView: View {
    @ObservedObject var viewModel : ChatViewModel
    @State var item: ChatBean
    @State private var showDel = false //删除
    @State private var hignBg = false //高亮背景
    @State private var select = false //选中
    let clickEdit: (Bool) -> Void

    var body: some View {
        HStack(alignment:.top, spacing: 10) {
            if viewModel.choose {
                chooseView
                Spacer()
            }
            VStack(alignment:.trailing) {
                contentView
                //引用内容
                if let target = item.targetChat {
                    ChatTargetView(bean: target)
                }
            }
            ChatAvatarVeiw(item: item)
        }.frame(maxWidth: .infinity,alignment: .topTrailing)
            .padding(EdgeInsets(top: 10, leading: 15, bottom: 20, trailing: 15))
            .background {
                if hignBg {
                    themeManager.themeColor.opacity(0.2)
                }
            }
            .contextMenu{
                if !viewModel.choose {
                    commonMenuContent
                }
            }
            .alert("温馨提示",isPresented:$showDel) {
                Button("取消",role: .cancel){}
                Button("确定",role: .destructive) {
                    viewModel.delChat(bean: item)
                }
            } message: {
                Text("是否确定要删除")
            }.onReceive(viewModel.$scrollChat.dropFirst()) { value in
                if value == item.objectId {
                    //搜索id一致，则高亮
                    withAnimation {
                        hignBg = true
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                        withAnimation {
                            hignBg = false
                        }
                    }
                }
            }
            .onChange(of: select) { newValue in
                item.select = newValue
            }
            .overlay {
                if viewModel.choose {
                    Color.clear
                        .contentShape(Rectangle())
                        .onTapGesture {
                            select = !select
                        }
                }
            }
    }
}

extension ChatItemUserView {
    var contentView : some View {
        VStack {
            if getBubble() != nil {
                //需要加id，不然刷新文字无法更新
                BubbleChatView(str: item.content ?? "", bean: getBubble() ?? BubbleBean()).id(item.content)
            } else {
                Text(item.content ?? "")
                    .font(.system(size: 14))
                    .foregroundStyle(.white)
                    .padding(.horizontal, 10)
                    .padding(.vertical, 5)
                    .frame(minHeight: 40)
                    .frame(minWidth: 40)
                    .background(themeManager.themeColor)
                    .cornerRadius(10)
                    .padding(.leading, 35)
            }
        }
    }
    func getBubble() -> BubbleBean?{
        let id = item.role?.bubbleId ?? ""
        return BubbleExt.getBubble(id: id)
    }
}

extension ChatItemUserView {
    //多选试图
    private var chooseView: some View {
        Group {
            if select == true {
                Image(.appIcCheckboxSelect)
                    .resizable()
                    .renderingMode(.template)
                    .foregroundColor(themeManager.themeColor)
                    .frame(width: 20,height: 20)
                    .padding(.top, 10)
            } else {
                Image(.appIcCheckbox)
                    .resizable()
                    .frame(width: 20,height: 20)
                    .padding(.top, 10)
            }
        }.onAppear{
            select = item.select ?? false
        }
    }
}

extension ChatItemUserView {
    // 将菜单内容抽离为一个计算属性，方便复用
    private var commonMenuContent: some View {
        Group {
            Button("删除") {
                onClickMenu(0)
            }
            Button("编辑") {
                onClickMenu(2)
            }
            Button("复制") {
                onClickMenu(3)
            }
            Button("装扮气泡") {
                onClickMenu(4)
            }
            Button("引用") {
                onClickMenu(6)
            }
            Button("多选") {
                onClickMenu(9)
            }
        }
    }
    
    func onClickMenu(_ type:Int) {
        hideKeyboard()
        switch(type) {
        case 0: //删除
            showDel = true
            break
        case 2://编辑
            clickEdit(true)
            showEditDialog(title: "编辑内容",hint: "请重新输入内容", content: item.content ?? "") { it in
                clickEdit(false)
                if !(it ?? "").isEmpty {
                    item.content = it
                    viewModel.saveChat(bean: item)
                }
            }
            break
        case 3://复制
            showToast("复制成功")
            copyClipboard(item.content)
            break
        case 4://装扮气泡
            pathManager.jump(type: JumpType.BUBBLE_MY,data: userManager.getUserId())
            break
        case 5:
            pathManager.jump(type: JumpType.BUBBLE_MY,data: userManager.getUserId())
            break
        case 6://引用
            if !AppStorageManager.shared.checkChatFuncToggle() {
                return
            }
            viewModel.targetChatBean = item
            break
        case 9://多选模式
            viewModel.setChooseMode()
            break
        default:
            break
        }
    }
}

#Preview {
    ChatItemUserView(viewModel: ChatViewModel(),item: ChatBean()){clickEdit in}.background(.bg)
}
